# -*- coding: utf-8 -*-
"""
股票预测模块 - 使用多种模型预测股票未来走势
"""
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import logging
from typing import Dict, List, Tuple, Optional
import warnings
warnings.filterwarnings('ignore')

# 机器学习相关
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression

# Prophet预测
try:
    from prophet import Prophet
    PROPHET_AVAILABLE = True
except ImportError:
    PROPHET_AVAILABLE = False
    logging.warning("Prophet未安装，将使用其他预测模型")

# 深度学习（简化版LSTM）
try:
    import tensorflow as tf
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import LSTM, Dense, Dropout
    TENSORFLOW_AVAILABLE = True
except ImportError:
    TENSORFLOW_AVAILABLE = False
    logging.warning("TensorFlow未安装，将使用传统机器学习模型")

from config import PREDICTION_CONFIG
from advanced_technical_analysis import AdvancedTechnicalAnalysis

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class StockPredictor:
    """股票预测器"""
    
    def __init__(self):
        self.config = PREDICTION_CONFIG
        self.scaler = MinMaxScaler()
        self.models = {}
        self.technical_analyzer = AdvancedTechnicalAnalysis()
        
    def predict_stock_trend(self, data: pd.DataFrame, stock_code: str) -> Dict:
        """预测股票趋势"""
        if data.empty or len(data) < self.config['min_history_days']:
            logger.warning(f"股票 {stock_code} 历史数据不足")
            return self._get_default_prediction()
        
        logger.info(f"开始预测股票 {stock_code} 未来 {self.config['forecast_days']} 天走势")
        
        # 数据预处理
        processed_data = self._preprocess_data(data)
        
        # 使用多种模型进行预测
        predictions = {}
        
        # 1. Prophet预测（如果可用）
        if PROPHET_AVAILABLE:
            predictions['prophet'] = self._prophet_predict(processed_data)
        
        # 2. 随机森林预测
        predictions['random_forest'] = self._random_forest_predict(processed_data)
        
        # 3. 线性回归预测
        predictions['linear_regression'] = self._linear_regression_predict(processed_data)
        
        # 4. LSTM预测（如果TensorFlow可用）
        if TENSORFLOW_AVAILABLE:
            predictions['lstm'] = self._lstm_predict(processed_data)
        
        # 5. 技术分析预测
        predictions['technical'] = self._technical_predict(processed_data)
        
        # 集成预测结果
        final_prediction = self._ensemble_predictions(predictions, processed_data)
        
        # 添加置信度评估
        final_prediction['confidence'] = self._calculate_confidence(predictions, processed_data)
        
        # 风险评估
        final_prediction['risk_assessment'] = self._assess_risk(processed_data, final_prediction)
        
        logger.info(f"股票 {stock_code} 预测完成")
        
        return final_prediction
    
    def _preprocess_data(self, data: pd.DataFrame) -> pd.DataFrame:
        """数据预处理"""
        df = data.copy()
        
        # 确保有必要的列
        required_cols = ['open', 'high', 'low', 'close', 'volume']
        for col in required_cols:
            if col not in df.columns:
                logger.error(f"缺少必要列: {col}")
                return pd.DataFrame()
        
        # 计算技术指标作为特征
        df['returns'] = df['close'].pct_change()
        df['volatility'] = df['returns'].rolling(20).std()
        df['sma_5'] = df['close'].rolling(5).mean()
        df['sma_20'] = df['close'].rolling(20).mean()
        df['sma_60'] = df['close'].rolling(60).mean()
        
        # 相对强弱指标
        df['rsi'] = self._calculate_rsi(df['close'])
        
        # 价格相对位置
        df['price_position'] = (df['close'] - df['low'].rolling(20).min()) / (df['high'].rolling(20).max() - df['low'].rolling(20).min())
        
        # 成交量指标
        df['volume_sma'] = df['volume'].rolling(20).mean()
        df['volume_ratio'] = df['volume'] / df['volume_sma']
        
        # 去除NaN值
        df = df.dropna()
        
        return df
    
    def _calculate_rsi(self, prices: pd.Series, period: int = 14) -> pd.Series:
        """计算RSI指标"""
        delta = prices.diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
        loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
        rs = gain / loss
        rsi = 100 - (100 / (1 + rs))
        return rsi
    
    def _prophet_predict(self, data: pd.DataFrame) -> Dict:
        """使用Prophet进行预测"""
        try:
            # 准备Prophet数据格式
            prophet_data = pd.DataFrame({
                'ds': data.index,
                'y': data['close']
            })
            
            # 创建Prophet模型
            model = Prophet(
                daily_seasonality=False,
                weekly_seasonality=True,
                yearly_seasonality=False,
                changepoint_prior_scale=0.05
            )
            
            # 训练模型
            model.fit(prophet_data)
            
            # 创建未来时间框架
            future = model.make_future_dataframe(periods=self.config['forecast_days'])
            
            # 预测
            forecast = model.predict(future)
            
            # 提取预测结果
            future_forecast = forecast.tail(self.config['forecast_days'])
            
            prediction = {
                'method': 'prophet',
                'predictions': future_forecast['yhat'].values,
                'upper_bound': future_forecast['yhat_upper'].values,
                'lower_bound': future_forecast['yhat_lower'].values,
                'dates': future_forecast['ds'].values,
                'trend': 'up' if future_forecast['yhat'].iloc[-1] > future_forecast['yhat'].iloc[0] else 'down'
            }
            
            return prediction
            
        except Exception as e:
            logger.error(f"Prophet预测失败: {e}")
            return self._get_default_prediction()
    
    def _random_forest_predict(self, data: pd.DataFrame) -> Dict:
        """使用随机森林进行预测"""
        try:
            # 准备特征和目标
            features = ['open', 'high', 'low', 'volume', 'sma_5', 'sma_20', 'rsi', 'volume_ratio']
            
            # 确保所有特征列存在
            available_features = [f for f in features if f in data.columns]
            
            if len(available_features) < 3:
                logger.warning("可用特征太少，使用默认预测")
                return self._get_default_prediction()
            
            X = data[available_features].values
            y = data['close'].values
            
            # 创建时间序列特征
            sequence_length = 10
            X_seq, y_seq = self._create_sequences(X, y, sequence_length)
            
            if len(X_seq) < 50:  # 数据太少
                return self._get_default_prediction()
            
            # 训练测试分割
            train_size = int(len(X_seq) * 0.8)
            X_train, X_test = X_seq[:train_size], X_seq[train_size:]
            y_train, y_test = y_seq[:train_size], y_seq[train_size:]
            
            # 重塑数据为2D（随机森林需要）
            X_train_2d = X_train.reshape(X_train.shape[0], -1)
            X_test_2d = X_test.reshape(X_test.shape[0], -1)
            
            # 训练随机森林模型
            model = RandomForestRegressor(n_estimators=100, random_state=42)
            model.fit(X_train_2d, y_train)
            
            # 预测未来价格
            last_sequence = X[-sequence_length:].reshape(1, -1)
            predictions = []
            
            current_sequence = last_sequence.copy()
            for _ in range(self.config['forecast_days']):
                pred = model.predict(current_sequence)[0]
                predictions.append(pred)
                
                # 更新序列（简化版本）
                # 实际应用中需要更复杂的特征更新逻辑
                
            prediction = {
                'method': 'random_forest',
                'predictions': predictions,
                'trend': 'up' if predictions[-1] > predictions[0] else 'down',
                'mae': mean_absolute_error(y_test, model.predict(X_test_2d)) if len(X_test) > 0 else 0
            }
            
            return prediction
            
        except Exception as e:
            logger.error(f"随机森林预测失败: {e}")
            return self._get_default_prediction()
    
    def _linear_regression_predict(self, data: pd.DataFrame) -> Dict:
        """使用线性回归进行预测"""
        try:
            # 使用简单的线性趋势预测
            close_prices = data['close'].values
            days = np.arange(len(close_prices))
            
            # 拟合线性趋势
            model = LinearRegression()
            model.fit(days.reshape(-1, 1), close_prices)
            
            # 预测未来
            future_days = np.arange(len(close_prices), len(close_prices) + self.config['forecast_days'])
            predictions = model.predict(future_days.reshape(-1, 1))
            
            prediction = {
                'method': 'linear_regression',
                'predictions': predictions,
                'trend': 'up' if model.coef_[0] > 0 else 'down',
                'slope': model.coef_[0]
            }
            
            return prediction
            
        except Exception as e:
            logger.error(f"线性回归预测失败: {e}")
            return self._get_default_prediction()
    
    def _lstm_predict(self, data: pd.DataFrame) -> Dict:
        """使用LSTM进行预测（简化版）"""
        try:
            # 准备数据
            close_prices = data['close'].values.reshape(-1, 1)
            scaled_data = self.scaler.fit_transform(close_prices)
            
            # 创建序列
            sequence_length = 60
            if len(scaled_data) < sequence_length + 30:
                return self._get_default_prediction()
            
            X, y = self._create_sequences(scaled_data, scaled_data[:, 0], sequence_length)
            
            # 训练测试分割
            train_size = int(len(X) * 0.8)
            X_train, X_test = X[:train_size], X[train_size:]
            y_train, y_test = y[:train_size], y[train_size:]
            
            # 构建LSTM模型
            model = Sequential([
                LSTM(50, return_sequences=True, input_shape=(sequence_length, 1)),
                Dropout(0.2),
                LSTM(50, return_sequences=False),
                Dropout(0.2),
                Dense(25),
                Dense(1)
            ])
            
            model.compile(optimizer='adam', loss='mean_squared_error')
            
            # 训练模型
            model.fit(X_train, y_train, batch_size=32, epochs=50, verbose=0)
            
            # 预测
            last_sequence = scaled_data[-sequence_length:].reshape(1, sequence_length, 1)
            predictions_scaled = []
            
            current_sequence = last_sequence.copy()
            for _ in range(self.config['forecast_days']):
                pred_scaled = model.predict(current_sequence, verbose=0)[0, 0]
                predictions_scaled.append(pred_scaled)
                
                # 更新序列
                current_sequence = np.roll(current_sequence, -1, axis=1)
                current_sequence[0, -1, 0] = pred_scaled
            
            # 反向缩放
            predictions_scaled = np.array(predictions_scaled).reshape(-1, 1)
            predictions = self.scaler.inverse_transform(predictions_scaled).flatten()
            
            prediction = {
                'method': 'lstm',
                'predictions': predictions,
                'trend': 'up' if predictions[-1] > predictions[0] else 'down'
            }
            
            return prediction
            
        except Exception as e:
            logger.error(f"LSTM预测失败: {e}")
            return self._get_default_prediction()
    
    def _technical_predict(self, data: pd.DataFrame) -> Dict:
        """基于通达信指标系统的技术分析预测"""
        try:
            # 使用新的高级技术分析系统
            tech_analysis = self.technical_analyzer.comprehensive_analysis(data)
            
            if not tech_analysis:
                return self._get_default_prediction()
            
            # 获取综合信号
            comprehensive_signal = tech_analysis.get('comprehensive_signal', {})
            signal_strength = comprehensive_signal.get('signal_strength', 0)
            signal_type = comprehensive_signal.get('signal_type', '观望')
            
            # 获取买卖线系统
            buy_sell_system = tech_analysis.get('buy_sell_system', {})
            
            # 获取多重EMA系统
            multi_ema_system = tech_analysis.get('multi_ema_system', {})
            
            # 获取指导线系统
            guidance_system = tech_analysis.get('guidance_system', {})
            
            current_price = data['close'].iloc[-1]
            
            # 基于通达信指标系统的高级预测逻辑
            trend_factor = self._calculate_advanced_trend_factor(
                signal_strength, buy_sell_system, multi_ema_system, guidance_system, data
            )
            
            # 计算波动率和市场情绪
            returns = data['close'].pct_change().dropna()
            volatility = returns.std() if len(returns) > 0 else 0.02
            
            # 基于EMA排列的支撑压力位
            support_resistance = self._calculate_support_resistance(multi_ema_system, current_price)
            
            # 生成预测序列 - 考虑技术指标的复杂交互
            predictions = []
            current_pred = current_price
            
            for i in range(self.config['forecast_days']):
                # 基础趋势预测
                base_trend = current_pred * (trend_factor - 1)
                
                # 支撑压力位影响
                sr_effect = self._calculate_support_resistance_effect(
                    current_pred, support_resistance, i
                )
                
                # 波动率衰减（随时间减弱）
                volatility_decay = max(0.3, 1 - i * 0.02)
                noise = np.random.normal(0, current_pred * volatility * 0.3 * volatility_decay)
                
                # 均值回归效应（基于指导线）
                if guidance_system and 'guidance_line' in guidance_system:
                    guidance_price = guidance_system['guidance_line'].iloc[-1] if len(guidance_system['guidance_line']) > 0 else current_price
                    mean_reversion = (guidance_price - current_pred) * 0.05 * (i + 1) / self.config['forecast_days']
                else:
                    mean_reversion = 0
                
                # 动量效应（短期延续，长期衰减）
                momentum_effect = self._calculate_momentum_effect(signal_strength, i)
                
                # 综合预测
                current_pred = current_pred + base_trend + sr_effect + noise + mean_reversion + momentum_effect
                predictions.append(max(current_pred, current_price * 0.5))  # 防止价格过度下跌
            
            # 计算预测趋势和置信度
            trend_info = self._analyze_prediction_trend(predictions, current_price)
            
            prediction = {
                'method': 'advanced_technical',
                'predictions': predictions,
                'trend': trend_info['trend'],
                'trend_strength': trend_info['strength'],
                'signal_type': signal_type,
                'signal_strength': signal_strength,
                'buy_sell_signal': buy_sell_system.get('current_signal', '无信号'),
                'ema_trend': multi_ema_system.get('current_trend', '震荡'),
                'confidence': comprehensive_signal.get('confidence', 0),
                'risk_level': tech_analysis.get('risk_assessment', {}).get('risk_level', '未知'),
                'support_resistance': support_resistance,
                'technical_score': self._calculate_technical_score(tech_analysis)
            }
            
            return prediction
            
        except Exception as e:
            logger.error(f"高级技术分析预测失败: {e}")
            return self._get_default_prediction()
    
    def _calculate_advanced_trend_factor(self, signal_strength: float, buy_sell: Dict, 
                                        multi_ema: Dict, guidance: Dict, data: pd.DataFrame) -> float:
        """计算高级趋势因子"""
        try:
            factors = []
            
            # 基础信号强度
            if signal_strength > 0.3:
                factors.append(1.020)  # 强势上涨
            elif signal_strength > 0.1:
                factors.append(1.010)  # 温和上涨
            elif signal_strength < -0.3:
                factors.append(0.980)  # 强势下跌
            elif signal_strength < -0.1:
                factors.append(0.990)  # 温和下跌
            else:
                factors.append(1.000)  # 震荡
            
            # 买卖线系统影响
            if buy_sell and 'buy_line' in buy_sell and 'sell_line' in buy_sell:
                buy_line = buy_sell['buy_line']
                sell_line = buy_sell['sell_line']
                if len(buy_line) > 0 and len(sell_line) > 0:
                    if buy_line.iloc[-1] > sell_line.iloc[-1]:
                        factors.append(1.008)  # 买线在上
                    else:
                        factors.append(0.992)  # 卖线在上
            
            # EMA多头/空头排列影响
            if multi_ema and 'bull_alignment' in multi_ema and 'bear_alignment' in multi_ema:
                bull_align = multi_ema['bull_alignment']
                bear_align = multi_ema['bear_alignment']
                if len(bull_align) > 0 and len(bear_align) > 0:
                    if bull_align.iloc[-1]:
                        factors.append(1.012)  # 多头排列
                    elif bear_align.iloc[-1]:
                        factors.append(0.988)  # 空头排列
            
            # 指导线系统影响
            if guidance and 'price_vs_guidance' in guidance:
                price_vs_guidance = guidance['price_vs_guidance']
                if len(price_vs_guidance) > 0:
                    if price_vs_guidance.iloc[-1]:
                        factors.append(1.005)  # 价格在指导线上方
                    else:
                        factors.append(0.995)  # 价格在指导线下方
            
            # 计算综合趋势因子
            if factors:
                trend_factor = np.mean(factors)
                # 限制趋势因子范围，避免过度预测
                trend_factor = max(0.97, min(1.03, trend_factor))
            else:
                trend_factor = 1.0
            
            return trend_factor
            
        except Exception as e:
            logger.error(f"趋势因子计算失败: {e}")
            return 1.0
    
    def _calculate_support_resistance(self, multi_ema: Dict, current_price: float) -> Dict:
        """计算支撑压力位"""
        try:
            levels = {'support': [], 'resistance': []}
            
            if multi_ema:
                # 使用EMA作为动态支撑压力位
                for key in ['p1_ema5', 'p2_ema8', 'p3_ema55']:
                    if key in multi_ema:
                        ema_line = multi_ema[key]
                        if len(ema_line) > 0:
                            ema_value = ema_line.iloc[-1]
                            if ema_value < current_price:
                                levels['support'].append(ema_value)
                            else:
                                levels['resistance'].append(ema_value)
            
            # 排序支撑压力位
            levels['support'] = sorted(levels['support'], reverse=True)[:3]  # 最近的3个支撑位
            levels['resistance'] = sorted(levels['resistance'])[:3]  # 最近的3个压力位
            
            return levels
            
        except Exception as e:
            logger.error(f"支撑压力位计算失败: {e}")
            return {'support': [], 'resistance': []}
    
    def _calculate_support_resistance_effect(self, price: float, sr_levels: Dict, day: int) -> float:
        """计算支撑压力位对价格的影响"""
        try:
            effect = 0
            
            # 支撑位影响
            for support in sr_levels.get('support', []):
                if abs(price - support) / support < 0.02:  # 接近支撑位
                    effect += price * 0.002 * (1 - day * 0.1)  # 影响随时间减弱
            
            # 压力位影响
            for resistance in sr_levels.get('resistance', []):
                if abs(price - resistance) / resistance < 0.02:  # 接近压力位
                    effect -= price * 0.002 * (1 - day * 0.1)  # 影响随时间减弱
            
            return effect
            
        except Exception as e:
            return 0
    
    def _calculate_momentum_effect(self, signal_strength: float, day: int) -> float:
        """计算动量效应"""
        try:
            # 动量在前几天较强，后续衰减
            momentum_decay = max(0.1, 1 - day * 0.05)
            momentum = signal_strength * 0.01 * momentum_decay
            return momentum
            
        except Exception as e:
            return 0
    
    def _analyze_prediction_trend(self, predictions: List[float], current_price: float) -> Dict:
        """分析预测趋势"""
        try:
            if not predictions:
                return {'trend': 'sideways', 'strength': 0}
            
            # 计算总体变化
            total_change = (predictions[-1] - predictions[0]) / predictions[0]
            
            # 计算趋势强度
            changes = []
            for i in range(1, len(predictions)):
                change = (predictions[i] - predictions[i-1]) / predictions[i-1]
                changes.append(change)
            
            avg_change = np.mean(changes) if changes else 0
            volatility = np.std(changes) if changes else 0
            
            # 趋势判断
            if total_change > 0.05:
                trend = 'strong_up'
                strength = min(abs(total_change) * 100, 30)
            elif total_change > 0.02:
                trend = 'up'
                strength = min(abs(total_change) * 100, 20)
            elif total_change < -0.05:
                trend = 'strong_down'
                strength = min(abs(total_change) * 100, 30)
            elif total_change < -0.02:
                trend = 'down'
                strength = min(abs(total_change) * 100, 20)
            else:
                trend = 'sideways'
                strength = abs(total_change) * 100
            
            return {
                'trend': trend,
                'strength': strength,
                'total_change_pct': total_change * 100,
                'avg_daily_change': avg_change * 100,
                'volatility': volatility * 100
            }
            
        except Exception as e:
            logger.error(f"趋势分析失败: {e}")
            return {'trend': 'sideways', 'strength': 0}
    
    def _calculate_technical_score(self, tech_analysis: Dict) -> float:
        """计算技术分析综合评分"""
        try:
            score = 50  # 基础分数
            
            # 综合信号贡献
            comprehensive_signal = tech_analysis.get('comprehensive_signal', {})
            signal_strength = comprehensive_signal.get('signal_strength', 0)
            score += signal_strength * 30  # 最大±30分
            
            # 买卖线系统贡献
            buy_sell_system = tech_analysis.get('buy_sell_system', {})
            current_signal = buy_sell_system.get('current_signal', '震荡')
            if current_signal == '看涨':
                score += 10
            elif current_signal == '看跌':
                score -= 10
            
            # 多重EMA系统贡献
            multi_ema_system = tech_analysis.get('multi_ema_system', {})
            current_trend = multi_ema_system.get('current_trend', '震荡整理')
            if '强势上涨' in current_trend:
                score += 15
            elif '温和上涨' in current_trend:
                score += 8
            elif '强势下跌' in current_trend:
                score -= 15
            elif '温和下跌' in current_trend:
                score -= 8
            
            # 限制评分范围
            score = max(0, min(100, score))
            
            return round(score, 1)
            
        except Exception as e:
            logger.error(f"技术评分计算失败: {e}")
            return 50.0
    
    def _create_sequences(self, X: np.ndarray, y: np.ndarray, sequence_length: int) -> Tuple[np.ndarray, np.ndarray]:
        """创建时间序列"""
        X_seq, y_seq = [], []
        for i in range(sequence_length, len(X)):
            X_seq.append(X[i-sequence_length:i])
            y_seq.append(y[i])
        return np.array(X_seq), np.array(y_seq)
    
    def _ensemble_predictions(self, predictions: Dict, data: pd.DataFrame) -> Dict:
        """集成多个预测结果"""
        if not predictions:
            return self._get_default_prediction()
        
        # 权重分配 - 增强技术分析权重
        weights = {
            'advanced_technical': 0.35,  # 提高技术分析权重
            'prophet': 0.25,
            'lstm': 0.2,
            'random_forest': 0.15,
            'linear_regression': 0.05
        }
        
        # 集成预测值
        ensemble_predictions = np.zeros(self.config['forecast_days'])
        total_weight = 0
        
        for method, pred_data in predictions.items():
            if 'predictions' in pred_data and len(pred_data['predictions']) == self.config['forecast_days']:
                weight = weights.get(method, 0.1)
                ensemble_predictions += np.array(pred_data['predictions']) * weight
                total_weight += weight
        
        if total_weight > 0:
            ensemble_predictions /= total_weight
        else:
            # 如果没有有效预测，使用当前价格
            current_price = data['close'].iloc[-1]
            ensemble_predictions = np.full(self.config['forecast_days'], current_price)
        
        # 计算趋势
        price_change = (ensemble_predictions[-1] - ensemble_predictions[0]) / ensemble_predictions[0]
        
        if price_change > 0.02:
            trend = "上涨"
            trend_strength = min(abs(price_change) * 100, 20)
        elif price_change < -0.02:
            trend = "下跌"  
            trend_strength = min(abs(price_change) * 100, 20)
        else:
            trend = "震荡"
            trend_strength = abs(price_change) * 100
        
        # 生成日期
        last_date = data.index[-1]
        future_dates = pd.date_range(start=last_date + timedelta(days=1), periods=self.config['forecast_days'])
        
        # 提取技术分析详细信息
        tech_pred = predictions.get('advanced_technical', {})
        
        result = {
            'predictions': ensemble_predictions.tolist(),
            'dates': future_dates.strftime('%Y-%m-%d').tolist(),
            'trend': trend,
            'trend_strength': trend_strength,
            'price_change_pct': price_change * 100,
            'individual_predictions': predictions,
            'current_price': data['close'].iloc[-1],
            # 技术分析详细信息
            'technical_details': {
                'signal_type': tech_pred.get('signal_type', '观望'),
                'signal_strength': tech_pred.get('signal_strength', 0),
                'buy_sell_signal': tech_pred.get('buy_sell_signal', '无信号'),
                'ema_trend': tech_pred.get('ema_trend', '震荡'),
                'technical_score': tech_pred.get('technical_score', 50),
                'support_resistance': tech_pred.get('support_resistance', {'support': [], 'resistance': []})
            }
        }
        
        return result
    
    def _calculate_confidence(self, predictions: Dict, data: pd.DataFrame) -> float:
        """计算预测置信度"""
        if not predictions:
            return 0.0
        
        # 基于模型一致性计算置信度
        trends = []
        for pred_data in predictions.values():
            if 'trend' in pred_data:
                trends.append(pred_data['trend'])
        
        if not trends:
            return 0.5
        
        # 计算趋势一致性
        from collections import Counter
        trend_counts = Counter(trends)
        max_count = max(trend_counts.values())
        consistency = max_count / len(trends)
        
        # 基于数据质量调整置信度
        data_quality = min(len(data) / self.config['min_history_days'], 1.0)
        
        confidence = consistency * data_quality * 0.8  # 最高80%置信度
        
        return round(confidence, 2)
    
    def _assess_risk(self, data: pd.DataFrame, prediction: Dict) -> Dict:
        """评估投资风险"""
        try:
            # 计算历史波动率
            returns = data['close'].pct_change().dropna()
            volatility = returns.std() * np.sqrt(252)  # 年化波动率
            
            # 最大回撤
            cumulative = (1 + returns).cumprod()
            max_drawdown = ((cumulative / cumulative.expanding().max()) - 1).min()
            
            # 风险等级
            if volatility > 0.4:
                risk_level = "高风险"
            elif volatility > 0.25:
                risk_level = "中高风险"
            elif volatility > 0.15:
                risk_level = "中等风险"
            else:
                risk_level = "低风险"
            
            # 预测风险
            pred_change = abs(prediction.get('price_change_pct', 0))
            if pred_change > 15:
                prediction_risk = "高"
            elif pred_change > 8:
                prediction_risk = "中"
            else:
                prediction_risk = "低"
            
            risk_assessment = {
                'volatility': round(volatility * 100, 2),
                'max_drawdown': round(max_drawdown * 100, 2),
                'risk_level': risk_level,
                'prediction_risk': prediction_risk,
                'recommendation': self._get_risk_recommendation(volatility, prediction)
            }
            
            return risk_assessment
            
        except Exception as e:
            logger.error(f"风险评估失败: {e}")
            return {'risk_level': '未知', 'recommendation': '谨慎投资'}
    
    def _get_risk_recommendation(self, volatility: float, prediction: Dict) -> str:
        """获取风险建议"""
        trend = prediction.get('trend', '震荡')
        confidence = prediction.get('confidence', 0.5)
        
        if volatility > 0.3:
            return "高风险资产，建议小仓位或观望"
        elif trend == "上涨" and confidence > 0.6:
            return "适合中长期持有，建议分批建仓"
        elif trend == "下跌":
            return "下跌趋势，建议减仓或观望"
        else:
            return "震荡行情，建议波段操作或观望"
    
    def _get_default_prediction(self) -> Dict:
        """获取默认预测结果"""
        return {
            'predictions': [0] * self.config['forecast_days'],
            'dates': [],
            'trend': '未知',
            'trend_strength': 0,
            'price_change_pct': 0,
            'confidence': 0,
            'individual_predictions': {},
            'current_price': 0,
            'risk_assessment': {'risk_level': '未知', 'recommendation': '数据不足，无法预测'}
        }

if __name__ == "__main__":
    # 测试预测功能
    predictor = StockPredictor()
    
    # 创建测试数据
    dates = pd.date_range(start='2023-01-01', end='2024-01-01', freq='D')
    test_data = pd.DataFrame({
        'open': np.random.randn(len(dates)).cumsum() + 100,
        'high': np.random.randn(len(dates)).cumsum() + 102,
        'low': np.random.randn(len(dates)).cumsum() + 98,
        'close': np.random.randn(len(dates)).cumsum() + 100,
        'volume': np.random.randint(1000, 10000, len(dates))
    }, index=dates)
    
    prediction = predictor.predict_stock_trend(test_data, "TEST001")
    print("预测结果:", prediction)
